package atm.com.service.bankcard;

import atm.com.mapper.BankcardMapper;
import atm.com.mapper.CashdispenserMapper;
import atm.com.mapper.UserMapper;
import atm.com.pojo.Bankcard;
import atm.com.pojo.Cashdispenser;
import atm.com.pojo.User;
import atm.com.util.AjaxResult;
import atm.com.util.CommonUtil;
import atm.com.util.MethodUtil;
import atm.com.util.RedisUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * BankCardServiceImpl class
 * @author di zhang
 * @date 2021/8/24
 */
@Service
public class BankCardServiceImpl implements BankCardServiceInf {

    @Autowired
    private BankcardMapper bankcardMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CashdispenserMapper cashdispenserMapper;

    @Override
    public String BankCardCheck(String bankcardNumber) {
        QueryWrapper <Bankcard> queryWrapper = new QueryWrapper <>();
        queryWrapper.lambda().eq(Bankcard::getBankcardNumber, bankcardNumber);
        CommonUtil commonUtil = new CommonUtil();
        Bankcard bankcard1 = bankcardMapper.selectOne(queryWrapper);
        if (bankcard1 == null) {
            //查看银行卡是否存在
            return commonUtil.STATE_NOT_FOUNT;
        }
        if (!bankcard1.getStatus().equals(0)) {
            //查看银行卡状态是否异常
            return commonUtil.STATE_FROZEN;
        }
        QueryWrapper <User> userWrapper = new QueryWrapper <>();
        userWrapper.lambda().eq(User::getUserId,bankcard1.getUserId());

        User user = userMapper.selectOne(userWrapper);
        if (!user.getStatus().equals(0)) {
            //查看银行卡持卡人 状态是否异常
            return commonUtil.STATE_FROZEN;
        }
            //所有条件都无误 返回true
        return CommonUtil.status.NORMAL;
    }

    @Override
    public AjaxResult BankCardLogin(Bankcard bankcard, HttpSession session, Cashdispenser cashdispenser) {
        QueryWrapper<Bankcard> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(Bankcard ::getBankcardNumber,bankcard.getBankcardNumber())
                .eq(Bankcard ::getBankcardPassword,bankcard.getBankcardPassword());
        CommonUtil commonUtil=new CommonUtil();
        Bankcard bankcard1=bankcardMapper.selectOne(queryWrapper);
        if(bankcard1 ==null){
            //银行卡密码错误
            if(session.getAttribute(bankcard.getBankcardNumber())== null){
                session.setAttribute(bankcard.getBankcardNumber(),1);
                System.out.println(session.getAttribute(bankcard.getBankcardNumber())+"===================");
                session.getAttribute(bankcard.getBankcardNumber());
                return  new AjaxResult(commonUtil.STATE_TIPS);
            }
            Integer i= (Integer)session.getAttribute(bankcard.getBankcardNumber());
            session.setAttribute(bankcard.getBankcardNumber(),++i);
            session.getAttribute(bankcard.getBankcardNumber());
            if((Integer)session.getAttribute(bankcard.getBankcardNumber())>= CommonUtil.errors.FREQUENCY){
                UpdateWrapper<Bankcard> updateWrapper =new UpdateWrapper <>();
                updateWrapper.eq("bankCard_number",bankcard.getBankcardNumber());
                Bankcard bankcard3=new Bankcard();
                bankcard3.setStatus(1);
                //修改状态不为1
                bankcardMapper.update(bankcard3,updateWrapper);
                return new AjaxResult(commonUtil.STATE_FROZEN);
            }
            return   new AjaxResult(commonUtil.STATE_TIPS);
        }
            //账号密码正确 写入日志表
            QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
            userQueryWrapper.lambda().eq(User ::getUserId,bankcard1.getUserId());
            User user=userMapper.selectOne(userQueryWrapper);

        //4.登录成功，那么就生成的令牌和登录信息存到redis，并返回给前台，前台进行存储（下次来访问的时候就就携带令牌，判断是否已经登录）
        //使用uuid生成token，避免重复
        String token = UUID.randomUUID().toString();

        //存到redis，并设置30分钟过期时间
         RedisUtils.INSTANCE.set(token, JSON.toJSONString(user),60*30 );

            Map<String, Object> map = new HashMap<>();
            map.put("uToken", token);
            map.put("tokenUser", user);

            //存提款机
            session.setAttribute(commonUtil.CASH_DISPENSER,cashdispenser);
            //存用户
            session.setAttribute(commonUtil.USER,user);
            //存银行卡
            session.setAttribute(commonUtil.BANK_CARD,bankcard1);
            MethodUtil methodUtil=new MethodUtil();
            //账号密码正确 存入session
            methodUtil.InsertJournal(session,CommonUtil.operate.LOGIN);
            //返回true 允许登录
            return  new AjaxResult(true,CommonUtil.status.NORMAL,map);
    }

    @Override
    public void UpdateBankCardStatue(Bankcard bankcard) {
        UpdateWrapper<Bankcard> updateWrapper =new UpdateWrapper <>();
        updateWrapper.eq("bankCard_number",bankcard.getBankcardNumber());
        bankcard.setStatus(1);
        //修改状态不为1
       bankcardMapper.update(bankcard,updateWrapper);
    }

    @Override
    public BigDecimal GetBanCardBalance(Bankcard bankcard) {
        QueryWrapper<Bankcard> queryWrapper=new QueryWrapper <>();
        queryWrapper.lambda().eq(Bankcard::getBankcardNumber,bankcard.getBankcardNumber());
        //根据银行卡 获取银行卡余额
        return bankcardMapper.selectOne(queryWrapper).getBankcardBalance();
    }

    @Override
    public String DepositBanCardBalance(BigDecimal money,Bankcard bankcard,Cashdispenser cashdispenser) {
        CommonUtil commonUtil=new CommonUtil();
        QueryWrapper<Cashdispenser> CashQueryWrapper=new QueryWrapper <>();
        CashQueryWrapper.lambda().eq(Cashdispenser::getCashDispenserId,cashdispenser.getCashDispenserId());
        Cashdispenser cashdispenser1 =cashdispenserMapper.selectOne(CashQueryWrapper);
        if(((cashdispenser1.getCashDispenserMoney().add(money)).compareTo(cashdispenser1.getCashDispenserTopLimit()))>=0){
            //提款机余额已满
            return  commonUtil.STATE_BALANCE_CASH_DISPENSER_FULL;
        }
        QueryWrapper<Bankcard> queryWrapper=new QueryWrapper <>();
        queryWrapper.lambda().eq(Bankcard::getBankcardNumber,bankcard.getBankcardNumber());
        Bankcard bankcard1= bankcardMapper.selectOne(queryWrapper);
        if(((bankcard1.getBankcardBalance().add(money)).compareTo(bankcard1.getBankcardTopLimit())>=0)){
            //银行卡余额已满
            return  commonUtil.STATE_BALANCE_FULL;
        }

        bankcard1.setBankcardBalance(bankcard1.getBankcardBalance().add(money));
        if(bankcardMapper.update(bankcard1,queryWrapper)<0){
            //存款失败
            return commonUtil.STATE_FAIL_SAVE;
        }
        UpdateWrapper<Cashdispenser> cashDispenserUpdateWrapper =new UpdateWrapper <>();
        cashDispenserUpdateWrapper.lambda().eq(Cashdispenser::getCashDispenserId,cashdispenser.getCashDispenserId());
        cashdispenser1.setCashDispenserMoney(cashdispenser1.getCashDispenserMoney().add(money));
        if((cashdispenserMapper.update(cashdispenser1,cashDispenserUpdateWrapper))<0 ){
            //存款失败
            return  commonUtil.STATE_FAIL_SAVE;
        }
        //存款成功
        return commonUtil.STATE_SUCCESS_SAVE;}

    @Override
    public String TakeBanCardBalance(BigDecimal money,Bankcard bankcard,Cashdispenser cashdispenser) {
        CommonUtil commonUtil=new CommonUtil();
        QueryWrapper<Cashdispenser> CashQueryWrapper=new QueryWrapper <>();
        CashQueryWrapper.lambda().eq(Cashdispenser::getCashDispenserId,cashdispenser.getCashDispenserId());
        Cashdispenser cashdispenser1 =cashdispenserMapper.selectOne(CashQueryWrapper);
        if(((cashdispenser1.getCashDispenserMoney().subtract(money)).compareTo(BigDecimal.ZERO)<=0)){
            //提款机余额不足
            return  commonUtil.STATE_BALANCE_CASH_DISPENSER;
        }
        QueryWrapper<Bankcard> queryWrapper=new QueryWrapper <>();
        queryWrapper.lambda().eq(Bankcard::getBankcardNumber,bankcard.getBankcardNumber());
        Bankcard bankcard1= bankcardMapper.selectOne(queryWrapper);
        if(((bankcard1.getBankcardBalance().subtract(money)).compareTo(BigDecimal.ZERO)<=0)){
            //银行卡余额不足
            return  commonUtil.STATE_BALANCE_INSUFFICIENT;
        }

        bankcard1.setBankcardBalance(bankcard1.getBankcardBalance().subtract(money));
        if(bankcardMapper.update(bankcard1,queryWrapper)<0){
            //取款失败
            return  commonUtil.STATE_FAIL_TAKE;
        }
        UpdateWrapper<Cashdispenser> cashDispenserUpdateWrapper =new UpdateWrapper <>();
        cashDispenserUpdateWrapper.lambda().eq(Cashdispenser::getCashDispenserId,cashdispenser.getCashDispenserId());
        cashdispenser1.setCashDispenserMoney(cashdispenser1.getCashDispenserMoney().subtract(money));
        if((cashdispenserMapper.update(cashdispenser1,cashDispenserUpdateWrapper))<0 ){
            //取款失败
            return   commonUtil.STATE_FAIL_TAKE;
        }
        //取款成功
        return commonUtil.STATE_SUCCESS_TAKE;}



}
